<?php

namespace App\Console\Commands\Renew;

use App\Library\FeiShu\SendFs;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Remote\Feishu\FeishuMsgRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\CommonService;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\System\SystemNotifyService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Kuafu\GeneralFs\BuildFs;

class MerchantRenewOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'renew:merchantOrder {shopCodes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '续签：商户通订单';

    /**
     * 成功执行门店集合
     *
     * @var array
     */
    public array $successShopCode = [];


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        $shopCodes   = $this->input->getArgument("shopCodes");
        $shopCodeMap = explode(",", $shopCodes);
        $this->output->info(sprintf("商户通续签订单续签 : 总计 %d 家门店 ", count($shopCodeMap)));
        $this->output->info(sprintf("门店信息 [ %s ]", implode(",", $shopCodeMap)));
        $this->output->info("开始执行.....");
        collect($shopCodeMap)->sort()->chunk(100)->each(function (Collection $shopCodeChunkMap) {
            OpenShopSignOrderModel::query()
                                  ->whereHas("mainProcessRel", function ($query) {
                                      $query->where("childLocationOrder", 0);
                                  })
                                  ->with("mainProcessRel")
                                  ->whereIn("shopCode", $shopCodeChunkMap->toArray())
                                  ->where("status", "<>", 0)
                                  ->get()
                                  ->sortBy("shopCode")
                                  ->each(function (OpenShopSignOrderModel $signOrderModel) {
                                      try {
                                          $this->comment("------+++++++++++++++++++++++++++++++++++-------");
                                          $this->info("门店 {$signOrderModel->shopCode} 执行 ...");

                                          //获取门店主订单
                                          $this->info("------- 获取门店主订单");
                                          $mainProcessRelModel = $this->getMainProcessModel($signOrderModel);

                                          //生成订单
                                          $this->info("------- 生成门店商户通续签单");
                                          list($orderNo, $preparationNo) = $this->addCostOrder($mainProcessRelModel->orderNo);

                                          //消息推送
                                          $this->info("------- 门店店长消息推送");
                                          $this->sendMsg(
                                              $signOrderModel->shopCode,
                                              $mainProcessRelModel->shopId,
                                              $orderNo,
                                              $preparationNo
                                          );

                                          array_push($this->successShopCode, $signOrderModel->shopCode);
                                          $this->info("门店 {$signOrderModel->shopCode} 执行完成");
                                      } catch (Exception $exception) {
                                          $this->error(vsprintf(
                                              "门店 [ %s ] 续签商户通订单生成失败 [ %s ]",
                                              [
                                                  $signOrderModel->shopCode,
                                                  $exception->getMessage()
                                              ]
                                          ));
                                      }
                                  });
        });

        $this->comment("------+++++++++++++++++++++++++++++++++++-------");
        $this->comment("------+++++++++++++++++++++++++++++++++++-------");
        $this->info(vsprintf("执行门店数量 %s , 门店数据 [%s]", [
            count($shopCodeMap),
            collect($shopCodeMap)->sort()->values()->implode(",")
        ]));
        $this->comment("------+++++++++++++++++++++++++++++++++++-------");
        $this->info(vsprintf("执行成功门店数量 %s , 门店数据 [%s]", [
            count($this->successShopCode),
            collect($this->successShopCode)->sort()->values()->implode(",")
        ]));
        $this->comment("------+++++++++++++++++++++++++++++++++++-------");
        $failShopCodes = array_diff($shopCodeMap, $this->successShopCode);
        $this->error(vsprintf("执行失败门店数量 %s , 门店数据 [%s]", [
            count($failShopCodes),
            implode(",", $failShopCodes)
        ]));

        logInfo(
            "商户通续费消息通知",
            collect([
                "stay"    => [
                    "count" => collect($shopCodeMap)->count(),
                    "list"  => collect($shopCodeMap)->sort()->values()->implode(","),
                ],
                "success" => [
                    "count" => collect($this->successShopCode)->count(),
                    "list"  => collect($this->successShopCode)->sort()->values()->implode(","),
                ],
                "error"   => [
                    "count" => collect(array_diff($shopCodeMap, $this->successShopCode))->count(),
                    "list"  => collect(array_diff($shopCodeMap, $this->successShopCode))->sort()->values()
                                                                                        ->implode(","),
                ]
            ]),
            true,
            true
        );

        return 0;
    }

    /**
     * 飞书消息推送
     *
     * @param OpenShopSignOrderModel $signOrderModel
     * @throws GuzzleException
     */
    public static function fsMsgSend(OpenShopSignOrderModel $signOrderModel)
    {
        try {
            $shopCollection = collect(RmsShopRemote::getShopInfosByCodes([$signOrderModel->shopCode])["shopList"]);
            $manager        = OpenShopOrderManagerModel::query()
                                                       ->where("mainProcessId", $signOrderModel->mainProcessRel->id)
                                                       ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                                                       ->first();

            $shopDetail          = $shopCollection->where("shopCode", $signOrderModel->shopCode)->first();
            $msgTemplateContents = view()->file(
                app_path("Remote/Feishu/FsTemplate/Renew") . "/MerchantRenewOrderNotifyTemplate.blade.php",
                [
                    "shopCode"       => $signOrderModel->shopCode,
                    "nowTime"        => date("Y-m-d H:i:s", time()),
                    "managerName"    => attributeGet($manager, "managerName", "-"),
                    "shopName"       => $shopDetail["name"],
                    "shopUserName"   => CommonService::getUserInfoHide($shopDetail["shopContact"] ?? "", 'name'),
                    "shopUserMobile" => CommonService::getUserInfoHide($shopDetail["shopMobile"] ?? "-", 'mobile'),
                ]
            )->render();


            if (checkEnv('prod')) {
                $fsIds = [
//                    '1f8c7761', // 理莎
                    '2c54915f', // 胡迪
                ];
            } else {
                $fsIds = [
                    '3fgc8798', // xm
                    '9acce1b7', // 风雪
                    '2c54915f', // 胡迪
                ];
            }

            collect($fsIds)->each(function ($fsId) use ($msgTemplateContents) {
                FeishuMsgRemote::getInstance()->sendInteractiveMsg(
                    $msgTemplateContents,
                    $fsId
                );
            });

            // 商户通续签订单通知机器人-推送群(上面单个人会一直换，之后统一推送群)
            BuildFs::newRobot(SendFs::ROBOT_MERCHANT_PAY_SUCCESS, BuildFs::MSG_TYPE_CARD)
                ->setCardContent(json_decode($msgTemplateContents, true))
                ->send();

        } catch (Exception $exception) {
            logException("商户通续签订单消息推送失败", $exception, $signOrderModel->toArray(), true, true);
        }
    }


    /**
     * 获取主订单
     *
     * @param OpenShopSignOrderModel $signOrderModel
     * @return Builder|Model|mixed|object
     * @throws Exception
     */
    public function getMainProcessModel(OpenShopSignOrderModel $signOrderModel)
    {
        if ($signOrderModel->mainProcessRel->childOrder == 0) {
            $mainProcessRelModel = $signOrderModel->mainProcessRel;
        } else {
            $mainProcessRelModel = OpenShopMainProcessModel::query()
                                                           ->where("id",
                                                               $signOrderModel->mainProcessRel->pid)
                                                           ->first();
        }

        if (empty($mainProcessRelModel)) {
            throw new Exception("查找主订单失败");
        }

        return $mainProcessRelModel;
    }

    /**
     * 生成订单
     *
     * @param string $orderNo
     * @return array
     */
    public function addCostOrder(string $orderNo): array
    {
        $id                          = SpaceDesignService::addCostOrder(
            $orderNo,
            0,
            0,
            150000,
            0
        );
        $spaceDesignCostMappingModel = OpenShopSpaceDesignCostMappingModel::query()->where("id", $id)->first();
        return [
            $spaceDesignCostMappingModel->orderNo,
            $spaceDesignCostMappingModel->preparationNo
        ];
    }

    /**
     * 消息推送
     *
     * @param string $shopCode
     * @param int $shopId
     * @param string $orderNo
     * @param string $preparationNo
     * @throws GuzzleException
     */
    public function sendMsg(
        string $shopCode,
        int $shopId,
        string $orderNo,
        string $preparationNo
    ) {
        try {
            //todo 获取门店店长用户信息
            $rmsShopManagers = RmsUserRemote::getShopManagerUserByShopId(
                    [],
                    [$shopCode],
                    true
                )['lists'] ?? [];

            //todo 发送app消息
            collect($rmsShopManagers)->pluck("userId")->each(function ($uid) use (
                $shopCode,
                $shopId,
                $orderNo,
                $preparationNo
            ) {
                self::msgSend(
                    "大众点评商户通续约提醒",
                    vsprintf(
                        "【夸父商家】尊敬的夸父伙伴您好，您的门店%s大众点评商户通费用订单已生成，请点击详情，完成支付。",
                        [$shopCode]
                    ),
                    $shopId,
                    $uid,
                    vsprintf("%sorder/space-design/5?orderNo=%s&preparationNo=%s", [
                        config('open-shop.m'),
                        $orderNo,
                        $preparationNo
                    ])
                );
            });

            //短信推送
            collect($rmsShopManagers)->pluck("mobile")->each(function ($mobile) use ($shopCode) {
                (new SmsService())->aliyunSend(
                    $mobile,
                    config('sms.template.merchantRenewOrder'),
                    ["shopCode" => $shopCode]
                );
            });
        } catch (Exception $exception) {
            $this->output->error(vsprintf(
                "消息推送失败 [%s] [%s]",
                [$shopCode, $exception->getMessage()]
            ));
        }
    }

    /**
     * @param string $title
     * @param string $summary
     * @param int $shopId
     * @param int $merchantUserId
     * @param string $url
     */
    public static function msgSend(string $title, string $summary, int $shopId, int $merchantUserId, string $url)
    {
        // 向商家发送报名消息
        $notify = SystemNotifyService::save(
            false,
            $title,
            SystemNotifyCenterModel::NOTIFY_TYPE_3,
            SystemNotifyCenterModel::NOTIFY_TARGET_1,
            '',
            $title,
            $url,
            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
            $summary,
            '',
            SystemNotifyCenterModel::IS_POPUP_ON,
            1,
            $shopId
        );
        SystemNotifyService::recordLog($notify, '创建消息');
        SystemNotifyService::preSend($notify->id, [$merchantUserId]);
    }
}
